package com.logic.meeting.core.app;

import android.app.Activity;
import android.os.Handler;

import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.Interceptor;

public class Configurator {

    private static final HashMap<Object, Object> ATMOS_CONFIGS = new HashMap<>();
    private static final ArrayList<Interceptor> INTERCEPTORS = new ArrayList<>();
    //    private static final ArrayList<IconFontDescriptor> ICONS = new ArrayList<>();
    private static final Handler HANDLER = new Handler();

    private Configurator() {

        ATMOS_CONFIGS.put(ConfigType.CONFIG_READY, false);
        ATMOS_CONFIGS.put(ConfigKeys.HANDLER, HANDLER);

    }

    public static Configurator getInstance() {
        return Holder.INSTANCE;
    }

    final HashMap<Object, Object> getAtmosConfigs() {
        return ATMOS_CONFIGS;
    }

    private static class Holder {
        private static final Configurator INSTANCE = new Configurator();
    }

    public final void configure() {
        Logger.addLogAdapter(new AndroidLogAdapter());
        ATMOS_CONFIGS.put(ConfigType.CONFIG_READY, true);
    }

    public final Configurator withInterceptor(Interceptor interceptor) {
        INTERCEPTORS.add(interceptor);
        ATMOS_CONFIGS.put(ConfigKeys.INTERCEPTOR, INTERCEPTORS);
        return this;
    }

    public final Configurator withApiHost(String host) {
        ATMOS_CONFIGS.put(ConfigKeys.API_HOST, host);
        return this;
    }

    public Configurator withWebHost(String host) {
        ATMOS_CONFIGS.put(ConfigKeys.WEB_HOST, host);
        return this;
    }

    private void checkConfiguration() {
        final boolean isReady = (boolean) ATMOS_CONFIGS.get(ConfigType.CONFIG_READY);
        if (!isReady) {
            throw new RuntimeException("Configuration is not ready,call configure");
        }
    }


    public Configurator withJavascriptInterface(String name) {
        ATMOS_CONFIGS.put(ConfigKeys.JAVASCRIPT_INTERFACE, name);
        return this;
    }

    //配置全局ACTIVITY
    public final Configurator withActivity(Activity activity) {
        ATMOS_CONFIGS.put(ConfigKeys.ACTIVITY, activity);
        return this;
    }

    @SuppressWarnings("unchecked")
    final <T> T getConfiguration(Object key) {
        checkConfiguration();
        final Object value = ATMOS_CONFIGS.get(key);
        if (value == null) {
            throw new NullPointerException(key.toString() + " IS NULL");
        }
        return (T) ATMOS_CONFIGS.get(key);
    }

}
